package cn.hinglo.gameclaw.admin.action;

import cn.hinglo.gameclaw.admin.service.VersionService;
import cn.hinglo.gameclaw.data.annotation.IgnoreToken;
import cn.hinglo.gameclaw.data.controller.BaseController;
import cn.hinglo.gameclaw.data.entity.Result;
import cn.hinglo.gameclaw.data.utils.CommonUtils;
import cn.hinglo.gameclaw.data.utils.FieldUtils;
import cn.hinglo.gameclaw.data.utils.FileImageUtils;
import cn.hinglo.gameclaw.user.bean.Version;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @createTime: 2018/6/4
 * @author: HingLo
 * @description: 娃娃机游戏的版本管理
 */
@RestController
@RequestMapping("/admin/v")
public class VersionAction extends BaseController {

    @Autowired
    private VersionService versionService;

    @GetMapping("/list")
    public Result list() {
        return success(versionService.listService());
    }

    @PostMapping("/add")
    public Result add(@RequestParam("apk") MultipartFile apk, String content) {
        if (apk == null || StrUtil.isBlank(content)) {
            return error("文件不能为空");
        }
        return result(versionService.addService(apk, content), "版本上传失败");
    }

    /**
     * 下载文件
     *
     * @param name 下载的文件名称
     */
    @GetMapping(value = "/download/{name}")
    @IgnoreToken
    public void download(@PathVariable(name = "name") String name, HttpServletResponse response) {
        String fileName = name + ".apk";
        if (StrUtil.isNotBlank(name)) {
            String path = FileImageUtils.readUrlUtils(FieldUtils.IMAGE_8) + fileName;
            try {
                CommonUtils.downloadApkUtils(fileName, path, request, response);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 检测最新的版本
     *
     * @return
     */
    @GetMapping("check")
    public Result check() {
        List<Version> list = versionService.listService();
        return success(list.get(list.size() - 1));
    }
}
